package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyCatalog;
import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.mapper.StrategyCatalogMapper;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.mapper.TravelContentMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyCatalogService;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {

    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper strategyContentMapper;

    @Override
    public void saveOrUpdate(StrategyDetail entity) {
        if(entity.getSequence() == null){
            Integer sequence = strategyDetailMapper
                    .selectSequenceByCatalogId(entity.getCatalog().getId());

            if(sequence == null){
                sequence = 0;
            }
            entity.setSequence(sequence + 1);
        }
        if(entity.getState() == StrategyDetail.STATE_RELEASE){
            entity.setReleaseTime(new Date());
        }
        StrategyContent strategyContent = entity.getStrategyContent();
        if(entity.getId()!=null){
            strategyDetailMapper.updateByPrimaryKey(entity);
            strategyContent.setId(entity.getId());
            strategyContentMapper.updateByPrimaryKey(strategyContent);
        }else {
            entity.setCreateTime(new Date());
            strategyDetailMapper.insert(entity);
            strategyContent.setId(entity.getId());
            strategyContentMapper.insert(strategyContent);
        }
    }

    @Override
    public String listById(Long strategyId) {
        return strategyContentMapper.selectByPrimaryKey(strategyId).getContent();
    }

    @Override
    public StrategyDetail get(Long id) {
        StrategyDetail detail = strategyDetailMapper.selectByPrimaryKey(id);
        StrategyContent strategyContent = strategyContentMapper.selectByPrimaryKey(id);
        detail.setStrategyContent(strategyContent);
        return detail;
    }

    @Override
    public PageInfo<StrategyDetail> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(qo);
        return new PageInfo<>(list);
    }
}
